import { mapMashupCoord } from './mapMashupCoord.util'
import { svgToSymbole, composeSvg, composeUseTag } from './svg.util'

export const mergeMashupSvg = (mashup, { compositions, graphics }) => {
  if (!mashup) return
  let useTags = '', symbolDefs = '';
  const completeMashup = composeMashup(mashup, compositions, graphics)
  const graphicCoords = mapMashupCoord(completeMashup)

  // svg convert to symbol code
  graphicCoords.forEach(graCoord => {
    const graphic = graphics.find(g => g.id === graCoord.graphicId)
    graphic && (symbolDefs += svgToSymbole(graphic))
  })

  // compose use tags 
  graphicCoords.forEach(graphicCoord => useTags += composeUseTag(graphicCoord))

  const boundSize = calcBoundSize(graphicCoords)
  const viewBox = `0 0 ${boundSize.width} ${boundSize.height}`
  return composeSvg(viewBox, symbolDefs, useTags)
}

function calcBoundSize(coordinates) {
  let groupWidth = 0; let groupHeight = 0;
  coordinates.forEach(coordinate => {
    const { x, y, width, height } = coordinate;
    if (groupWidth < x + width) { groupWidth = x + width }
    if (groupHeight < y + height) { groupHeight = y + height }
  })
  return { width: groupWidth, height: groupHeight }
}


function composeMashup(mashup, compositions, graphics) {
  mashup.groups.forEach((group, index) => {
    if (group.type === 'graphic') {
      const graphic = graphics.find(g => g.id === group.graphicId)
      group.svgCode = graphic.svgCode
    }
    if (group.type === 'composition') {
      const compo = compositions.find(c => c.id === group.compositionId)
      for (const direct in compo.componests) {
        const { graphicId } = compo.componests[direct].component
        const graphic = graphics.find(g => g.id === group.graphicId)
        compo.componests[direct].svgCode = graphic.svgCode
      }
      mashup.groups[index].composition = compo
    }
  })
  return mashup
}

